#include "CScene.h"
#include "CCore.h"
#include "CInputManager.h"
#include "CVideoManager.h"

CScene::CScene()
{

}

bool CScene::Initialize()
{
    return true;
}

void CScene::Execute()
{

}

CScene::~CScene()
{
    Release();
}

bool CScene::Release()
{
    int i;
    for (i = (int)Layers.size()-1; i >= 0; i--){
        Layers[i]->Release();
        delete Layers[i];
    }
    Layers.clear();
    for (i = (int)TileImages.size()-1; i >= 0; i--)
        CVideoManager::getInstance()->DeleteImage(&TileImages[i]);

    TileImages.clear();
    return true;
}

void CScene::Update()
{
    int iSize = (int)Layers.size();
    for (int i = 0; i < iSize; i++)
        Layers[i]->Update();
}

void CScene::Draw()
{
    int iSize = (int)Layers.size();
    for (int i = 0; i < iSize; i++){
        if (Layers[i]->bVisible)
            Layers[i]->Draw();
    }
}

bool CScene::DeleteLayer(CLayer **p_Layer)
{
    if (p_Layer && *p_Layer){
        for (int i = (int)Layers.size()-1; i >=0; i--){
            if (Layers[i] == *p_Layer){
                Layers[i]->Release();
                delete Layers[i];
                *p_Layer = NULL;
                Layers.erase(Layers.begin()+i);
                return true;
            }
        }
    }
    return false;
}

void CScene::Scroll(const CVector &cScroll)
{
    for (int i = (int)Layers.size()-1; i >=0; i--)
        Layers[i]->Scroll(cScroll);
}

CLayer * CScene::CreateLayer(const CVector &cBrickSize,const CVector &cNumBricks)
{
    CLayer *p_Layer = CreateLayer(cBrickSize);
    if (p_Layer){
        p_Layer->CreateBricks(cNumBricks);
        return p_Layer;
    }
    return NULL;
}


CLayer * CScene::CreateLayer(int iw,int ih)
{
    return CreateLayer(CVector(iw,ih));
}

CLayer * CScene::CreateLayer(const CVector &cBrickSize)
{
    CLayer *p_Layer = new CLayer();
    if (p_Layer){
        p_Layer->BrickSize	= cBrickSize;
        p_Layer->pr_Scene	= this;
        Layers.push_back(p_Layer);
        return p_Layer;
    }
    return NULL;
}

int CScene::AddTileImage(const std::string& cp_chFileName, const CVector& cFrameSize)
{
    if (!cp_chFileName.empty()){
        CImage *p_Image = CVideoManager::getInstance()->LoadImage(cp_chFileName);
        if (p_Image){
            p_Image->SetFrameSize(cFrameSize);
            TileImages.push_back(p_Image);
            return (int)TileImages.size()-1;
        }else
            return -1;
    }

    return -1;
}

void CScene::CleanUp()
{

}
